﻿var newBakModel = new Object();
var rowid;
$(document).ready(function () {
    //контексное меню
    var contextMenu = $("#Menu").jqxMenu({ width: 120, height: 86, autoOpenPopup: false, theme: theme, mode: 'popup' });
    $("#jTable").bind('contextmenu', function () {
        return false;
    });

    //кнопка биндинга для добавления
    $('#addButtom').jqxButton({ width: '100px', theme: theme, heigh: 50 });
    $('#addButtom').bind('click', function () {
        newBakModel.Id = null;
        newBakModel.SerialNumber = null;
        newBakModel.BackId = null;
        newBakModel.BackSerialNumber = null;
        newBakModel.Date = new Date();
        newBakModel.Mesuring = new Object({ 20010000001: 1 });
        $('#jqxWindow').jqxWindow('setTitle', 'Добавить новую запись');
        $('#jqxWindow').jqxWindow('show');
        $("#dropDownFilter3").jqxDropDownList({ promptText: "Выберите свободный БАК:", theme: theme });
    });

    // handle context menu clicks.
    $("#Menu").bind('itemclick', function (event) {
        var args = event.args;
        var rowindex = $("#jTable").jqxGrid('getselectedrowindex');
        rowid = $("#jTable").jqxGrid('getrowid', rowindex);
        if (args.id == "edit") {
            $.ajax({
                url: '/data/car',
                data: { id: rowid },
                contentType: 'application/json; charset=UTF-8',
                type: "GET",
                success: function (data) {
                    newBakModel.Id = data.CarId;
                    newBakModel.Date = data.Date;
                    newBakModel.SerialNumber = data.SerialNumber;
                    newBakModel.Creator = data.Creator;
                    newBakModel.Type = data.Type;
                    newBakModel.OperationOrganization = data.OperationOrganization;
                    newBakModel.Mesuring = data.Mesuring;
                    newBakModel.BackId = data.BackId;
                    newBakModel.BackSerialNumber = data.BackSerialNumber;

                    $('#jqxWindow').jqxWindow('setTitle', 'Редактирование');

                    $("#jqxWindow").jqxWindow('show');

                    $("#dropDownFilter3").jqxDropDownList({ promptText: newBakModel.BackSerialNumber });

                    var dropDownContent = '<div style="position: relative; margin-left: 3px; margin-top: 5px;">' + data.TypeOfCar + '</div>';
                    $("#dropDownFilter1").jqxDropDownButton('setContent', dropDownContent);

                    dropDownContent = '<div style="position: relative; margin-left: 3px; margin-top: 5px;">' + data.Organization + '</div>';
                    $("#dropDownFilter4").jqxDropDownButton('setContent', dropDownContent);

                },
                error: function (data) {
                    alert(data.responseText);
                }
            });

        }
        else if (args.id == "add") {
            newBakModel.BackSerialNumber = '';
            $('#addButtom').click();
        } else {
            $("#jqxWindow").jqxWindow('close');
            $('#DeleteWindow').jqxWindow('open');

        }
        $("#Menu").jqxMenu('close');
    });
    $("#jTable").bind('rowclick', function (event) {
        if (event.args.rightclick) {
            $("#jTable").jqxGrid('selectrow', event.args.rowindex);
            var scrollTop = $(window).scrollTop();
            var scrollLeft = $(window).scrollLeft();
            contextMenu.jqxMenu('open', parseInt(event.args.originalEvent.clientX) + 5 + scrollLeft, parseInt(event.args.originalEvent.clientY) + 5 + scrollTop);
            return false;
        }
    });


    $("#serialNumber").jqxInput({ placeHolder: "Серийный номер", height: 25, width: '100%', minLength: 1, theme: theme});

    //создается окно на добавление/редактирование
    $('#jqxWindow').jqxWindow({
        height: 500,
        width: 320,
        autoOpen: false,
        resizable: false, theme: theme,
        animationType: 'none',
        showCloseButton: false,
        cancelButton: $('#CancelButton'),
        initContent: function () {
            
            $("#serialNumber").val(newBakModel.SerialNumber);
            $('#dropDownFilter3').val(newBakModel.BackSerialNumber);
            $('#dateOfCreate').jqxDateTimeInput('setDate', new Date(newBakModel.Date));
            var sourceBak =
                {
                    datatype: "json",
                    datafields: [
                        { name: 'SerialNumber' },
                        { name: 'Id' }
                    ],
                    id: 'id',
                    url: '/data/bak?free=true'
                };
            var dataAdapterBak = new $.jqx.dataAdapter(sourceBak);
            $("#dropDownFilter3").jqxDropDownList({
                source: dataAdapterBak,
                autoDropDownHeight: true, theme: theme,
                displayMember: "SerialNumber",
                valueMember: "Id",
                width: '100%',
                height: 25,
                openDelay: 0
            });
            var item = $('#treeFilter2').jqxTree('getItems');
            for (var VAR in item) {
                var curItem = item[VAR];
                var state = false;
                if ((curItem.hasItems == false) && (curItem.subtreeElement != null)) {
                    var valueMesuring = 0;
                    if (newBakModel.Mesuring != null)
                        if (newBakModel.Mesuring[curItem.id] != null) {
                            valueMesuring = newBakModel.Mesuring[curItem.id];
                            state = true;
                        }
                    $('#m_' + curItem.id).jqxNumberInput('val', valueMesuring);
                    $('#treeFilter2').jqxTree('checkItem', $("#" + curItem.id)[0], state);
                }
            }
        }
    });

    $('#okButton').jqxButton({ width: '100px', theme: theme, heigh: 50 });
    $('#cancelButton').jqxButton({ width: '100px', theme: theme, heigh: 50 });
    $('#SubmitButton').jqxButton({ width: '100px', theme: theme, heigh: 50 });
    $('#CancelButton').jqxButton({ width: '100px', theme: theme, heigh: 50 });

    $("#dateOfCreate").jqxDateTimeInput({
        width: '100%',
        height: 30, theme: theme,
        culture: 'ru-RU',
        textAlign: "center",
        maxDate: new $.jqx._jqxDateTimeInput.getDateTime(new Date())
    });

    //создаем окно для диалога удаления
    $('#DeleteWindow').jqxWindow({
        width: 400,
        height: 120,
        resizable: false,
        isModal: true,
        autoOpen: false, theme: theme,
        cancelButton: $('#cancelButton'),
        okButton: $('#okButton'),
        initContent: function () {
            $('#DeleteWindow').jqxWindow({ title: ("Удаление БАК-а") });
        }
    });
    //биндим кнопку удаления
    $("#okButton").bind('click', function () {
        $.ajax({
            url: '/data/car/' + rowid,
            contentType: 'application/json; charset=UTF-8',
            type: "DELETE",
            success: function () {
                $('#jTable').jqxGrid('updatebounddata');
            },
            error: function (data) {
                alert(data.responseText);
            }
        });
    });

    //создаем модуль валидации
    $('#BakConfig').jqxValidator({
        rules: [
            { input: '#serialNumber', message: 'Серийный номер не указан!', action: 'keyup, blur, mousemove', rule: 'required' },
            {
                input: '#dropDownFilter1',
                message: 'Выберите тип!',
                action: 'keyup, blur, mouseover',
                rule: function () {
                    return newBakModel.Type != null;
                }
            },
            {
                input: '#dropDownFilter3', message: 'БАК не указан!', action: 'keyup, blur, mousemove', rule: function () {
                    return newBakModel.BackId != null;
                }
            },
            {
                input: '#dropDownFilter4',
                message: 'Выберите эксплуатирующую организацию!',
                action: 'keyup, blur, mouseover',
                rule: function () {
                    return newBakModel.OperationOrganization != null;
                }
            }
        ], theme: theme,
        onSuccess: function () {
            newBakModel.SerialNumber = $('#serialNumber').val();
            newBakModel.Date = $("#dateOfCreate").jqxDateTimeInput('getDate');

            var oldStates = newBakModel.Mesuring;
            newBakModel.Mesuring = new Array();


            for (var VAR in oldStates) {
                if ($("#" + VAR)[0] == null) {
                    var newItem = new Object();
                    newItem.MesuringId = VAR;
                    var val = $('#m_' + VAR).jqxNumberInput('val');
                    if (val != null) {
                        newItem.TimeOut = val;
                    } else {
                        newItem.TimeOut = oldStates[VAR];
                    }
                    newBakModel.Mesuring.push(newItem);
                }
                else {
                    var newItem = new Object();
                    var curItem = $('#treeFilter2').jqxTree('getItem', $("#" + VAR)[0]);
                    if (curItem.checked) {
                        newItem.MesuringId = VAR;
                        newItem.TimeOut = $('#m_' + VAR).jqxNumberInput('val');
                        newBakModel.Mesuring.push(newItem);
                    }
                }
            }
            var item = $('#treeFilter2').jqxTree('getItems');
            for (var VAR in item) {
                var curItem = item[VAR];
                if (curItem.subtreeElement != null && curItem.hasItems == false) { //если измерение, то
                    if (curItem.checked && oldStates[curItem.id] == null) {
                        var newItem = new Object();
                        newItem.MesuringId = curItem.id;
                        newItem.TimeOut = $('#m_' + curItem.id).jqxNumberInput('val');
                        newBakModel.Mesuring.push(newItem);
                    }
                }
            }
            //alert(JSON.stringify(newBakModel.Mesuring));
            $.ajax({
                url: '/data/car',
                type: 'PUT',
                data: JSON.stringify(newBakModel),
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function () {
                    $('#jTable').jqxGrid('updatebounddata');
                    $('#jqxWindow').jqxWindow('close');

                },
                error: function (data) {
                    alert(JSON.stringify(newBakModel));
                    alert(data.responseText);
                }
            });
        }
    });

    //запросы создания деревьев в диалоговых окнах
    $.ajax({
        url: '/data/Classificator/30000000000',
        type: "GET",
        contentType: 'application/json; charset=UTF-8',
        success: function (data) {
            $("#treeFilter1").jqxTree({
                width: 300, theme: theme,
                source: data
            });
        },
        error: function () {
            alert('Невозможно подключиться к серверу данных.');
        }
    });

    $.ajax({
        url: '/data/Classificator/10020000000',
        type: "GET",
        contentType: 'application/json; charset=UTF-8',
        success: function (data) {
            $("#treeFilter4").jqxTree({
                width: 300, theme: theme,
                source: data
            });
        },
        error: function () {
            alert('Невозможно подключиться к серверу данных.');
        }
    });

    $.ajax({
        url: '/data/Classificator/20000000000',
        type: "GET",
        contentType: 'application/json; charset=UTF-8',
        success: function (data) {
            $("#treeFilter2").jqxTree({
                width: 400, theme: theme,
                checkboxes: true,
                hasThreeStates: true,
                source: data
            });
        },
        error: function () {
            alert('Невозможно подключиться к серверу данных.');
        }
    });

    //фильтр 1 для Type
    $('#treeFilter1').bind('expand', function (event) {
        var $element = $(event.args.element);
        var loader = false;
        var loaderItem = null;
        var children = $element.find('li');
        $.each(children, function () {
            var item = $('#treeFilter1').jqxTree('getItem', this);
            if (item.label == 'Loading...') {
                loaderItem = item;
                loader = true;
                return false;
            }
            ;
        });
        if (loader) {
            $.ajax({
                url: '/data/Classificator',
                data: { id: loaderItem.value },
                contentType: 'application/json; charset=UTF-8',
                success: function (data, status, xhr) {
                    if (data.length > 0) {
                        $('#treeFilter1').jqxTree('addTo', data, $element[0]);
                        $('#treeFilter1').jqxTree('removeItem', loaderItem.element);
                    } else {
                        $('#treeFilter1').jqxTree('removeItem', loaderItem.element);
                    }
                },
                error: function () {
                    alert("Не удалось подключиться к серверу");
                }
            });
        }
    });
    $("#dropDownFilter1").jqxDropDownButton({ width: '100%', theme: theme, height: 25 });
    $('#treeFilter1').bind('select', function (event) {
        var args = event.args;
        var item = $('#treeFilter1').jqxTree('getItem', args.element);
        if (item.hasItems == false) {
            var dropDownContent = '<div style="position: relative; margin-left: 3px; margin-top: 5px;">' + item.label + '</div>';
            newBakModel.Type = item.id;
            $("#dropDownFilter1").jqxDropDownButton('setContent', dropDownContent);
        }
    });
    //фильтр 2 для Expluat
    $('#treeFilter4').bind('expand', function (event) {
        var $element = $(event.args.element);
        var loader = false;
        var loaderItem = null;
        var children = $element.find('li');
        $.each(children, function () {
            var item = $('#treeFilter4').jqxTree('getItem', this);
            if (item.label == 'Loading...') {
                loaderItem = item;
                loader = true;
                return false;
            }
            ;
        });
        if (loader) {
            $.ajax({
                url: '/data/Classificator',
                data: { id: loaderItem.value },
                contentType: 'application/json; charset=UTF-8',
                success: function (data, status, xhr) {
                    if (data.length > 0) {
                        $('#treeFilter4').jqxTree('addTo', data, $element[0]);
                        $('#treeFilter4').jqxTree('removeItem', loaderItem.element);
                    } else {
                        $('#treeFilter4').jqxTree('removeItem', loaderItem.element);
                    }
                },
                error: function () {
                    alert("Не удалось подключиться к серверу");
                }
            });
        }
    });
    $("#dropDownFilter4").jqxDropDownButton({ width: '100%', theme: theme, height: 25 });
    $('#treeFilter4').bind('select', function (event) {
        var args = event.args;
        var item = $('#treeFilter4').jqxTree('getItem', args.element);
        if (item.hasItems == false) {
            var dropDownContent = '<div style="position: relative; margin-left: 3px; margin-top: 5px;">' + item.label + '</div>';
            newBakModel.OperationOrganization = item.id;
            $("#dropDownFilter4").jqxDropDownButton('setContent', dropDownContent);
        }
    });

    //фильтр 3 для Измерений
    $('#treeFilter2').bind('expand', function (event) {
        var $element = $(event.args.element);
        var loader = false;
        var loaderItem = null;
        var children = $element.find('li');
        $.each(children, function () {
            var item = $('#treeFilter2').jqxTree('getItem', this);
            if (item.label == 'Loading...') {
                loaderItem = item;
                loader = true;
                return false;
            }
            ;
        });
        if (loader) {
            $.ajax({
                url: '/data/Classificator',
                data: { id: loaderItem.value },
                contentType: 'application/json; charset=UTF-8',
                success: function (data, status, xhr) {
                    if (data.length > 0) {
                        for (var VAR in data) {
                            data[VAR].label = data[VAR].label + "<span class='numericInput' id='m_" + data[VAR].id + "'></span>";
                            if (newBakModel.Mesuring != null) {
                                if (newBakModel.Mesuring[data[VAR].id] != null) {
                                    data[VAR].checked = true;
                                }
                            }
                        }
                        $('#treeFilter2').jqxTree('addTo', data, $element[0]);
                        $('#treeFilter2').jqxTree('removeItem', loaderItem.element);
                        $('.numericInput').jqxNumberInput({
                            width: '50px',
                            height: '15px',
                            digits: 3, decimalDigits: 0
                        });
                        for (var VAR in data) {
                            if (newBakModel.Mesuring != null)
                                if (newBakModel.Mesuring[data[VAR].id] != null) {
                                    $('#m_' + data[VAR].id).jqxNumberInput('val', newBakModel.Mesuring[data[VAR].id]);

                                }
                        }
                        $('.numericInput').bind('contextmenu', function (e) {
                            if ($(e.target).parents('.jqx-tree').length > 0) {
                                return false;
                            }
                            return true;
                        });
                    } else {
                        $('#treeFilter2').jqxTree('removeItem', loaderItem.element);
                    }
                },
                error: function () {
                    alert("Не удалось подключиться к серверу");
                }
            });
        }
    });
    $("#dropDownFilter2").jqxDropDownButton({ width: '100%', theme: theme, height: 25 });

    //кнопка биндинга для подтверждения
    $('#SubmitButton').bind('click', function () {
        $('#BakConfig').jqxValidator('validate');
    });


    $("#dropDownFilter3").bind('select', function (event) {
        if (event.args) {
            var item = event.args.item;
            if (item) {
                newBakModel.BackId = item.value;
                newBakModel.BackSerialNumber = item.label;
            }
        }
    });

    // prepare the data для таблицы
    var source =
        {
            datatype: "json",
            datafields: [
                { name: 'CarId' },
                { name: 'SerialNumber' },
                { name: 'TypeOfCar' },
                { name: 'BackSerialNumber' },
                { name: 'Organization' },
                { name: 'Date', type: 'date' }
            ],
            url: '/data/car',
            root: 'Rows',
            id: "CarId",
            beforeprocessing: function (data) {
                source.totalrecords = data.TotalRows;
            }
        };
    var dataadapter = new $.jqx.dataAdapter(source);
    // initialize таблицы
    $("#jTable").jqxGrid(
        {
            width: "98%",
            source: dataadapter,
            autoheight: true,
            pageable: true,
            virtualmode: true,
            pagesizeoptions: ['10', '20', '30'],
            enabletooltips: true, theme: theme,
            rendergridrows: function () {
                return dataadapter.records;
            },
            columns: [
                { text: 'Серийный номер', datafield: 'SerialNumber' },
                { text: 'Тип автомобиля', datafield: 'TypeOfCar' },
                { text: 'Серийный номер подключенного БАК-а', datafield: 'BackSerialNumber' },
                { text: 'Эксплуатирующая организация', datafield: 'Organization' },
                { text: 'Время', datafield: 'Date', cellsformat: "dd.MM.yyyy" }
            ]
        });

    function isRightClick(event) {
        var rightclick;
        if (!event) var event = window.event;
        if (event.which) rightclick = (event.which == 3);
        else if (event.button) rightclick = (event.button == 2);
        return rightclick;
    }
});
